/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package util;

import org.apache.http.HttpEntity;
import org.apache.http.HttpStatus;
import org.apache.http.StatusLine;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

import java.io.IOException;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpDelete;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPut;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;


/**
 *
 * @author wudihua
 */
public class HttpUtil {
    
    private static final Logger logger = LogManager.getLogger(HttpUtil.class.getName());
    
    public static final String ContentType_xml = "application/fhir+xml;charset=UTF-8";

    public static final String ContentType_json = "application/fhir+json;charset=UTF-8";
    
    //http post xmlString
    public static String sendPost(String url, String string, String contentType){
        CloseableHttpClient httpclient = HttpClients.createDefault();
        logger.info("url:{}",url);
        HttpPost httpPost = new HttpPost(url);
        //设置请求的报文头部的编码
        //httpPost.setHeader("Content-Type", "application/fhir+xml;charset=UTF-8");
        httpPost.setHeader("Content-Type", contentType);
        StringEntity entity = new StringEntity(string, "UTF-8");
        httpPost.setEntity(entity);
        CloseableHttpResponse response = null;

        try {

            response = httpclient.execute(httpPost);
            StatusLine status = response.getStatusLine();
            int state = status.getStatusCode();
            //System.out.println(state);
            if (state != 404 || state != 500) {
                HttpEntity responseEntity = response.getEntity();
                String strResult = EntityUtils.toString(responseEntity);
                //System.out.println("response: "+ strResult);
                logger.info("response: {}", strResult);
                return strResult;
            } else {
                logger.error("error 请求返回:" + state + "(" + url + ")");
            }
        } catch (IOException ex) {
            System.out.println(ex);
            ex.printStackTrace();
            logger.error("error url:{}, {}", url, ex);
        } finally {
            if (response != null) {
                try {
                    response.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            try {
                httpclient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return null;
    }
    
    //http post xmlString
    public static String sendPut(String url, String string, String contentType){
        CloseableHttpClient httpclient = HttpClients.createDefault();
        logger.info("url:{}",url);
        HttpPut httpPut = new HttpPut(url);
        //设置请求的报文头部的编码
        //httpPut.setHeader("Content-Type", "application/fhir+xml;charset=UTF-8");
        httpPut.setHeader("Content-Type", contentType);
        StringEntity entity = new StringEntity(string, "UTF-8");
        httpPut.setEntity(entity);
        CloseableHttpResponse response = null;

        try {

            response = httpclient.execute(httpPut);
            StatusLine status = response.getStatusLine();
            int state = status.getStatusCode();
            System.out.println(state);
            if (state == HttpStatus.SC_OK) {
                HttpEntity responseEntity = response.getEntity();
                String strResult = EntityUtils.toString(responseEntity);
                logger.info("response: {}", strResult);
                return strResult;
            } else {
         
                logger.error("error 请求返回:" + state + "(" + url + ")");
            }
        } catch (IOException ex) {
            ex.printStackTrace();
            logger.error("error url:{}, {}", url, ex);
        } finally {
            if (response != null) {
                try {
                    response.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            try {
                httpclient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return null;
    }
    
    
    //http get 
    public static String sendGet(String url, String contentType) {
        logger.info("url:{}",url);
        try {
            CloseableHttpClient httpclient = HttpClients.createDefault();
            HttpGet httpGet = new HttpGet(url);  
            //设置期望服务端返回的编码
            httpGet.setHeader("Accept", contentType);
            HttpResponse response = httpclient.execute(httpGet);
            if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {   
                String strResult = EntityUtils.toString(response.getEntity(),"utf-8");  
                logger.info("get result:{}", strResult);
                return strResult;  
            }  
        } catch (IOException ex) {
            ex.printStackTrace();
            logger.error("error url:{}, {}", url, ex);
        }
        return null;
    }
    
    //http delete
    public static String sendDelete(String url, String contentType) {
       logger.info("url:{}",url);
        try {
            CloseableHttpClient httpclient = HttpClients.createDefault();
            HttpDelete httpDelete = new HttpDelete(url);  
            //设置期望服务端返回的编码
//            httpDelete.setHeader("Accept", "application/xml;charset=UTF-8");
            httpDelete.setHeader("Accept", contentType);
            HttpResponse response = httpclient.execute(httpDelete);
            if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {   
                String strResult = EntityUtils.toString(response.getEntity(),"utf-8"); 
                logger.info("get result:{}", strResult);
                return strResult;  
            }  
        } catch (IOException ex) {
            ex.printStackTrace();
            logger.error("error url:{}, {}", url, ex);
        }
        return null;
    }
    
    
}
